##parameters=data=None

from Products.KnowledgeEngine.Utils.helpers import parseCSV
from Products.KnowledgeEngine.KERLProcessor import parseKERL

if not data:
    return """
<form method="POST" enctype="multipart/form-data">
    <input type="file" name="data"/>
    <input type="submit"/>
</form>
"""


model = context.getComponentByIdentity("model01185231899708906676503")

components = model.getDescendantsByInstanceOf('Component')

mapping = {} # oldId -> componentIdentity

options = {} # componentIdentity -> { value: optionIdentity }

for component in components:
    if component.isInstanceOf("Section"):
        #print " --- " + component.title_or_id()
        continue
    elif component.isInstanceOf("Option"):
       # print " + " + component.getContent()
        select = component.aq_parent
        options.setdefault( select.getIdentity(), {} )[ component.getContent() ] = component.getIdentity()
        
    else:
        mapping[ component.getId() ] = component.getIdentity()
        
    
mapping['dateentered'] = mapping['dob']
    
    
ass = context.knowledgeengine_assessmentstorageservice    
    
for row in parseCSV(data):     
    
    username = row['id']
    assessment = ass.createAssessment( model, username, repositoryIdentity='admin' )
    
    for key, value in row.items():
        #print key
        if key in mapping:
            if value.startswith("("):                
                
                # Is a multipl choice question
                
                thisOptions = []
                for item in parseKERL( value ):
                    optionIdentity = options[ mapping[key] ][ item ]
                    option = context.getComponentByIdentity( optionIdentity )
                    option.updateAssessmentState( assessment, 'true' )
                    
                #value = thisOptions
            else:
                # Is a regular text question
                
                component = context.getComponentByIdentity( mapping[key] )
                if component.isInstanceOf('Selection'):
                    if not value: continue
                    option = context.getComponentByIdentity( options[mapping[key]][value] )
                    option.updateAssessmentState( assessment, 'true' )
                else:
                    component.updateAssessmentState( assessment, value )
                
                                                            
                                                            
            print "%s = %s" % ( key, value )
                
                
    assessment.setName( username )                
    ass.saveAssessment( assessment )       
            
            
    
print "Done"    
return printed    